<!--
 * @Author: ZAL 2177624751@qq.com
 * @Date: 2025-02-14 09:16:37
 * @LastEditors: ZAL 2177624751@qq.com
 * @LastEditTime: 2025-03-31 15:04:55
 * @FilePath: \shop_app_vue3\pages\user\components\address.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE/
-->
<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <u-search
        v-model="searchText"
        placeholder="搜索收货地址"
        :show-action="false"
        :disabled="filteredAddressList.length === 0"
        @change="onSearch"
      ></u-search>
    </view>

    <!-- 地址列表 -->
    <scroll-view 
      scroll-y 
      class="address-list"
      @scrolltolower="loadMore"
      v-if="filteredAddressList.length > 0"
    >
      <view 
        class="address-item"
        v-for="(item, index) in filteredAddressList"
        :key="item.id"
        @click="selectAddress(item)"
      >
        <view class="address-info">
          <view class="user-info">
            <text class="name">{{item.receiverName}}</text>
            <text class="phone">{{item.receiverPhone}}</text>
            <text class="tag" v-if="item.isDefault === 1">默认</text>
          </view>
          <view class="address-detail">
            <u-icon name="map" size="32rpx" color="#666"></u-icon>
            <text>{{item.province}}{{item.city}}{{item.district}}{{item.detailAddress}}</text>
          </view>
        </view>
        <view class="address-actions">
          <view class="action-btn" @click.stop="setDefault(item)" v-if="item.isDefault !== 1">
            <text>设为默认</text>
          </view>
          <view class="action-btn" @click.stop="handleEdit(item)">
            <u-icon name="edit-pen" size="40rpx"></u-icon>
          </view>
          <view class="action-btn" @click.stop="handleDelete(item)">
            <u-icon name="trash" size="40rpx"></u-icon>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <image
        src="/static/images/empty-address.png"
        class="empty-image"
        mode="aspectFit"
      />
      <text class="empty-text">暂无收货地址</text>
      <text class="empty-desc">添加地址更方便购物哦</text>
    </view>

    <!-- 底部按钮 -->
    <view class="footer">
      <u-button
        type="primary"
        color="#00b578"
        @click="handleAddAddress"
        :loading="loading"
      >新增收货地址</u-button>
    </view>

    <!-- 操作确认弹窗 -->
    <u-modal
      :show="showDeleteModal"
      title="删除确认"
      content="确定要删除该地址吗？"
      @confirm="confirmDelete"
      @cancel="showDeleteModal = false"
    ></u-modal>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAddressStore } from '@/store/addressStore'

const addressStore = useAddressStore()
const searchText = ref('')
const loading = ref(false)
const showDeleteModal = ref(false)
const currentItem = ref(null)

// 过滤后的地址列表
const filteredAddressList = computed(() => {
  const list = addressStore.getAddressList
  if (!searchText.value) return list
  return list.filter(item => 
    item.receiverName.includes(searchText.value) || 
    item.receiverPhone.includes(searchText.value) ||
    `${item.province}${item.city}${item.district}${item.detailAddress}`.includes(searchText.value)
  )
})

// 获取地址列表
const getAddressList = async () => {
  loading.value = true
  try {
    await addressStore.loadAddressList()
  } catch (error) {
    uni.showToast({
      title: '获取地址列表失败',
      icon: 'none'
    })
  }
  loading.value = false
}

// 搜索地址
const onSearch = (value) => {
  searchText.value = value
}

// 加载更多
const loadMore = () => {
  // 暂不实现分页加载
}

// 选择地址
const selectAddress = (item) => {
  addressStore.setCurrentAddress(item)
  const pages = getCurrentPages()
  const prevPage = pages[pages.length - 2]
  if (prevPage && prevPage.onAddressSelected) {
    uni.navigateBack({
      success: () => {
        prevPage.onAddressSelected(item)
      }
    })
  }
}

// 设置默认地址
const setDefault = async (item) => {
  try {
    await addressStore.setAddressAsDefault(item.id)
    uni.showToast({
      title: '设置成功',
      icon: 'success'
    })
  } catch (error) {
    uni.showToast({
      title: '设置失败',
      icon: 'none'
    })
  }
}

onMounted(() => {
  getAddressList()
})

// 跳转到添加地址页面
const handleAddAddress = () => {
  uni.navigateTo({
    url: '/pages/user/components/addAddress'
  })
}

// 编辑地址
const handleEdit = (item) => {
  console.log('要编辑的地址数据:', item)
  const query = {
    id: item.id,
    receiverName: item.receiverName,
    receiverPhone: item.receiverPhone,
    province: item.province,
    city: item.city,
    district: item.district,
    detailAddress: item.detailAddress,
    isDefault: item.isDefault
  }
  
  console.log('构造的query对象:', query)
  
  // 将对象转换为查询字符串
  const queryString = Object.entries(query)
    .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
    .join('&')
  
  console.log('最终的跳转URL:', `/pages/user/components/addAddress?${queryString}`)
  
  uni.navigateTo({
    url: `/pages/user/components/addAddress?${queryString}`
  })
}

// 删除地址
const handleDelete = (item) => {
  currentItem.value = item
  showDeleteModal.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!currentItem.value) return
  
  try {
    await addressStore.deleteExistingAddress(currentItem.value.id)
    uni.showToast({
      title: '删除成功',
      icon: 'success'
    })
  } catch (error) {
    uni.showToast({
      title: '删除失败',
      icon: 'none'
    })
  } finally {
    showDeleteModal.value = false
    currentItem.value = null
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: env(safe-area-inset-bottom);
}

.search-bar {
  background-color: #00b578;
  padding: 20rpx 30rpx;
  
  :deep(.u-search) {
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 40rpx;
  }
}

.address-list {
  height: calc(100vh - 180rpx);
  padding: 20rpx;
  
  .address-item {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    
    .address-info {
      .user-info {
        display: flex;
        align-items: center;
        margin-bottom: 16rpx;
        
        .name {
          font-size: 32rpx;
          font-weight: bold;
          margin-right: 20rpx;
        }
        
        .phone {
          font-size: 28rpx;
          color: #666;
        }
        
        .tag {
          margin-left: auto;
          background-color: #00b578;
          color: #fff;
          font-size: 24rpx;
          padding: 4rpx 12rpx;
          border-radius: 4rpx;
        }
      }
      
      .address-detail {
        display: flex;
        align-items: flex-start;
        font-size: 28rpx;
        color: #333;
        line-height: 1.5;
        
        text {
          flex: 1;
          margin-left: 12rpx;
        }
      }
    }
    
    .address-actions {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      margin-top: 20rpx;
      padding-top: 20rpx;
      border-top: 2rpx solid #f5f5f5;
      
      .action-btn {
        display: flex;
        align-items: center;
        padding: 10rpx 20rpx;
        color: #666;
        font-size: 28rpx;
        
        text {
          color: #00b578;
        }
        
        &:active {
          opacity: 0.7;
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 200rpx;
  
  .empty-image {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 40rpx;
  }
  
  .empty-text {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 16rpx;
  }
  
  .empty-desc {
    font-size: 28rpx;
    color: #999;
  }
}

.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx 40rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  :deep(.u-button) {
    height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    color: #00b578;
    
    &:active {
      transform: scale(0.98);
    }
  }
}
</style>
